//
//  SWWeatherView.m
//  SimpleWeather
//
//  Created by  James on 14-12-11.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "SWWeatherView.h"
#import "SWConstants.h"
#import "SWManager.h"
#import "SWCondition.h"

#import <ReactiveCocoa.h>
#import <LBBlurredImage/UIImageView+LBBlurredImage.h>

@interface SWWeatherView () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property NSDateFormatter *hourlyFormatter;
@property NSDateFormatter *dailyFormatter;

@end

@implementation SWWeatherView

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (void)viewWillAppear:(BOOL)animated
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIImage *img = _backgroundImageView.image;
    [_blurImageView setImageToBlur:img blurRadius:10 completionBlock:nil];
    [_tableView setSeparatorColor:[UIColor colorWithWhite:1 alpha:0.2]];
    
    _hourlyFormatter = [[NSDateFormatter alloc] init];
    _hourlyFormatter.dateFormat = @"H a";
    
    _dailyFormatter = [[NSDateFormatter alloc] init];
    _dailyFormatter.dateFormat = @"EEEE";
    
    [self loadWeatherConditions];
    [self loadWeatherForcast];
    
    
    	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return MIN([SWManager sharedManager].hourlyForecast.count, 6)+1;
    }
    else
    {
        return MIN([SWManager sharedManager].dailyForecast.count, 6)+1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor colorWithWhite:0 alpha:0.2];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.textColor = [UIColor whiteColor];
    
    if (indexPath.section == 0)
    {

        if (indexPath.row == 0)
        {
            cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
            cell.textLabel.text = @"Hourly Forecast";
            cell.detailTextLabel.text = @"";
        }
        else
        {
            SWCondition *weather = [[SWManager sharedManager].hourlyForecast objectAtIndex:indexPath.row - 1];
            cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18];
            cell.detailTextLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
            NSString *time = [self.hourlyFormatter stringFromDate:weather.date];
            cell.textLabel.text = time;
            NSString *temp = [NSString stringWithFormat:@"%.0f°",weather.temperature.floatValue];
            cell.detailTextLabel.text = temp;
            cell.imageView.image = [UIImage imageNamed:[weather imageName]];
            cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
        }
    }
    else
    {
        
        if (indexPath.row == 0)
        {
            cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
            cell.textLabel.text = @"Daily Forecast";
            cell.detailTextLabel.text = @"";
        }
        else
        {
            SWCondition *weather = [[SWManager sharedManager].dailyForecast objectAtIndex:indexPath.row - 1];
            cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:18];
            cell.detailTextLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
            cell.textLabel.text = [self.dailyFormatter stringFromDate:weather.date];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.0f° / %.0f°",
                                         weather.tempHigh.floatValue,
                                         weather.tempLow.floatValue];
            cell.imageView.image = [UIImage imageNamed:[weather imageName]];
            cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
            
        }
    }
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger cellCount = [self.tableView.dataSource tableView:tableView numberOfRowsInSection:indexPath.section];
    
    return SCREEN_HEIGHT/(CGFloat)cellCount;
}

#pragma mark - Scroll view delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat height = scrollView.bounds.size.height;
    CGFloat position = MAX(scrollView.contentOffset.y, 0.0);
    // 2
    CGFloat percent = MIN(position / height, 1.0);
    // 3
    self.blurImageView.alpha = percent;
}

#pragma mark - Actions

- (void)loadWeatherConditions
{
    SWManager *ma = [SWManager sharedManager];
    
    __block SWWeatherView *weakSelf = self;
    
    [[[ma updateCurrentConditions] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(SWCondition *newCondition){
        weakSelf.loadingLabel.hidden = YES;
        weakSelf.temperatureLabel.text = [NSString stringWithFormat:@"%.0f",newCondition.temperature.floatValue];
        weakSelf.conditionsLabel.text = [newCondition.locationName capitalizedString];
        weakSelf.hiloLabel.text = [NSString stringWithFormat:@"%.0f°/%.0f°",newCondition.tempHigh.floatValue,newCondition.tempLow.floatValue];
        NSString *imageName = [newCondition imageName];
        weakSelf.iconView.image = [UIImage imageNamed:imageName];
    }];
}

- (void)loadWeatherForcast
{
    SWManager *ma = [SWManager sharedManager];
    __block SWWeatherView *weakSelf = self;
    [[[ma updateHourlyForecast] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSArray *hourForecast){
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
    
    [[[ma updateDailyForecast] deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSArray *hourForecast){
        [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
    }];
}
@end
